package com.ktjiaoyu.crm;

import com.ktjiaoyu.crm.pojo.User;
import com.ktjiaoyu.crm.service.UserService;
import jakarta.annotation.Resource;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.*;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.concurrent.TimeUnit;
@SpringBootTest
@RunWith(SpringRunner.class)
public class RedisTemlateTester {
    @Resource
    private UserService userService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;//操作字符串数据
    @Resource
    private RedisTemplate redisTemplate;//操作对象数据
    //操作字符串:
    @Test
    public void testString(){
        stringRedisTemplate.opsForValue().set("name","czkt");
        Assert.assertEquals("czkt",stringRedisTemplate.opsForValue().get("name"));
    }
    //操作实体:
    @Test
    public void testObj(){
        User user=new User("czkt","123456",null,null);
        ValueOperations<String,User> operations = redisTemplate.opsForValue();
        operations.set("ktjiaoyu.crm.user.czkt",user);
        User u = operations.get("ktjiaoyu.crm.user.czkt");
        System.out.println("user.usrName:"+u.getUsrName());
    }
    //超时失效
    @Test
    public void testExpire() throws InterruptedException{
        User user=new User("czkt","123456",null,null);
        ValueOperations<String,User> operations = redisTemplate.opsForValue();
        operations.set("expire",user,100, TimeUnit.MILLISECONDS);
        Thread.sleep(1000);
        boolean exists = redisTemplate.hasKey("expire");
        if(exists){
            System.out.println("exists is true");
        }else{
            System.out.println("exists is false");
        }
    }
    //操作哈稀
    @Test
    public void testHash(){
        HashOperations<String,Object,Object> hash=redisTemplate.opsForHash();
        hash.put("hash","name","ktjiaoyu");
        String value = (String) hash.get("hash","name");
        System.out.println("hash name value:"+value);
    }
    @Test
    public void testList(){
        ListOperations<String,String> list=redisTemplate.opsForList();
        list.leftPush("list","accp");
        list.leftPush("list","bdqn");
        list.leftPush("list","czkt");
        String value =list.rightPop("list");
        System.out.println("list value:"+value.toString());
    }
    @Test
    public void testGetUser(){
        User user=userService.getUser(2L);
        System.out.println("user:"+user.toString());
    }
}
